package main.java;
import javax.swing.*;

import java.awt.*;
import java.util.ArrayList;

/**
 * Created by dse on 12/14/2014.
 */
public class Board extends JPanel {

    public static final int CELL_SIZE = 10;
    private final int rows = 10;
    private final int cols = 20;
    ArrayList<Bacteria> bacteriaList;
    ArrayList<Bacteria> babies, dead;

    Board() {
        super();
        setBackground(Color.white);
        bacteriaList = new ArrayList<Bacteria>();
        babies = new ArrayList<Bacteria>();
        dead = new ArrayList<Bacteria>();
        setPreferredSize(new Dimension(cols * CELL_SIZE, rows * CELL_SIZE));
        bacteriaList.add(new Bacteria(this, 3, 5));//toa do hthi cua con dau tien
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Bacteria bacteria: bacteriaList) {
            bacteria.draw(g);
        }
    }

    public void tick() {
        dead = new ArrayList<Bacteria>();
        babies = new ArrayList<Bacteria>();

        for (Bacteria bacteria: bacteriaList) {
            bacteria.tick();
        }
        bacteriaList.addAll(babies);
        bacteriaList.removeAll(dead);
    }

    public void addBaby(Bacteria baby) {
        if (baby != null) babies.add(baby);
    }

    public void addDead(Bacteria deadCreature) {
        if (deadCreature != null) dead.add(deadCreature);
    }

    public boolean emptyCell(int x, int y) {
        if (x < 0 || y < 0 || x >= cols || y >= rows) return false;

        for (Bacteria bacteria : bacteriaList) {
            if (bacteria.atPosition(x, y)) {
                return false;
            }
        }
        for (Bacteria bacteria : babies) {//ktra o cua con co trong k
            if (bacteria.atPosition(x, y)) {
                return false;
            }
        }
        return true;
    }

    public String getPopulation() {
        return String.format("%d", bacteriaList.size());
    }
}